package com.ruge.config;


import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfig {

    private final DynamicDataSourceProperties properties;

    public DynamicDataSourceConfig(DynamicDataSourceProperties properties) {
        this.properties = properties;
    }

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractDataSourceProvider(null) {
            @Override
            public Map<String, DataSource> loadDataSources() {
                Map<String, DataSource> dataSources = new HashMap<>();

                // 加载主数据源
                String primaryKey = properties.getPrimary();
                DataSourceProperty primaryProp = properties.getDatasource().get(primaryKey);
                if (primaryProp != null) {
                    dataSources.put(primaryKey, createDataSource(primaryProp));
                }

                // 加载其他数据源
                properties.getDatasource().forEach((key, prop) -> {
                    if (!key.equals(primaryKey)) {
                        dataSources.put(key, createDataSource(prop));
                    }
                });

                return dataSources;
            }

            private DataSource createDataSource(DataSourceProperty primaryProp) {
                HikariDataSource dataSource = new HikariDataSource();
                dataSource.setJdbcUrl(primaryProp.getUrl());
                dataSource.setUsername(primaryProp.getUsername());
                dataSource.setPassword(primaryProp.getPassword());
                dataSource.setDriverClassName(primaryProp.getDriverClassName());
                // 可以根据需要设置更多 HikariCP 的配置
                return dataSource;
            }

        };
    }
}